using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

using WPS.Libraries.CssDom;

namespace WPS.Modules.StyleLibrary
{
	/// <summary>
	/// Dumps the editable CSS file while prepending all selectors with "div.preview".
	/// Used on the overview page.
	/// </summary>
	public partial class IncludeCss : System.Web.UI.Page
	{
		#region Template controls

		/// <summary>Contencts of the loaded css files as plain string.</summary>
		protected string CssContents;

		#endregion

		#region Page events

		/// <summary>
		/// Page load event.
		/// </summary>
		/// <param name="sender">Sender</param>
		/// <param name="e">Event args</param>
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Authenticate user
			StyleLibraryIntegration cms = new StyleLibraryIntegration();
			if(!cms.CheckAccess())
			{
				Response.Redirect(cms.GetLoginPage(), true);
			}

			HttpContext.Current.Response.ContentType = "text/css";
			HttpContext.Current.Response.Expires = -1;
			
			LoadCssFiles();
		}

		#endregion

		#region Put your local functions here

		private void LoadCssFiles()
		{
			this.CssContents = "";
			IStyleLibraryIntegration cms = new StyleLibraryIntegration();
			LoadCssFile(Server.MapPath(cms.GetEditableCssWebPath()), "div.preview");
		}

		/// <summary>
		/// Load CSS file and prefix all rules with the specified prefix.
		/// </summary>
		/// <param name="filename"></param>
		/// <param name="rulePrefix"></param>
		/// <returns></returns>
		private bool LoadCssFile(string filename, string rulePrefix)
		{
			CSSStyleSheet css = new CSSStyleSheet();
			if(css.Load(filename))
			{

				for(int i = 0; i < css.cssRules.length; i++)
				{
					CSSStyleRule rule = (CSSStyleRule)css.cssRules[i];

					// Add prefix to rule and rules in the selector, then add to output.
					this.CssContents += rulePrefix + " " + rule.selectorText.Replace(",", "," + rulePrefix + " ");

					// Add rule contents to output.
					this.CssContents += "\n{\n" + rule.style.cssText + "}\n\n";
				}
			}
			else
			{
				return false;
			}

			return true;
		}

		#endregion

	}
}
